package com.cq.controller;

import com.alibaba.fastjson.JSON;
import com.cq.pojo.Result;
import com.cq.pojo.User;
import com.cq.pojo.WXSession;
import com.cq.service.MailService;
import com.cq.service.UserService;
import com.cq.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.*;

/**
 * @Author: 悠久的苍穹
 * @Date: 2021/1/21 20:22
 * @Description: 用户控制层
 * @Version: 1.0
 */
@Controller
public class UserController {


    @Autowired
    UserService userService;

    @Autowired
    MailService mailService;

    @ResponseBody
    @PostMapping("/wxLogin")
    public Result wxLogin(@RequestBody Map<String,Object> map){
        Result result = new Result();
        String openid = map.get("openid").toString();
        String nickname = map.get("nickname").toString();
        String avatarUrl = map.get("avatarUrl").toString();
        Integer gender = Integer.parseInt(map.get("gender").toString());
        User user = userService.findUserByOpenId(openid,nickname);
        if(user!=null){
            result.setMsg(user.getUuid());
            result.setCode(200);
        }else{
            String uuid = UUID.randomUUID().toString().replace("-","");
            User user1 = new User();
            user1.setUuid(uuid);
            user1.setOpenid(openid);
            user1.setNickname(nickname);
            user1.setAvatarUrl(avatarUrl);
            user1.setGender(gender);
            System.out.println(user1);
            int i = userService.addUser(user1);
            if(i==1){
                result.setCode(200);
                result.setMsg(uuid);
            }else{
                result.setCode(500);
                result.setMsg("添加失败");
            }
        }
        return result;
    }

    @ResponseBody
    @PostMapping("/user/auth")
    public Result getUser(@RequestBody Map<String,Object> map){
        Result result = new Result();
        String uuid = map.get("uuid").toString();
        String email = map.get("email").toString();
        String idcard_front = map.get("idcard_front").toString();
        String idcard_tail = map.get("idcard_tail").toString();
        String qrcode = map.get("qrcode").toString();
        User user = new User();
        user.setUuid(uuid);
        user.setEmail(email);
        user.setIdcard_front(idcard_front);
        user.setIdcard_tail(idcard_tail);
        user.setQrcode(qrcode);
        System.out.println(user);
        int i = userService.updateUser(user);
        if (i==1){
            result.setCode(200);
            result.setMsg("提交成功，请关注邮件进度");
        }else{
            result.setCode(500);
            result.setMsg("提交失败，请重新填写");
        }
        return result;
    }

    @ResponseBody
    @GetMapping("/getUsers")
    public Result getUsers(@RequestParam int page,
                           @RequestParam int limit) {
        Result result = new Result();
        int count = userService.getCount();
        List<User> userList = userService.findUsers(page,limit);
        result.setCode(0);
        result.setCount(count);
        result.setData(userList);
        return result;
    }

    @GetMapping("/authUser/{uuid}")
    public String authUser(@PathVariable("uuid") String uuid,Model model){
        User user = userService.findUserByUUid(uuid);
        model.addAttribute("user",user);
        return "user/user/userform.html";
    }

    @RequestMapping("/send")
    @ResponseBody
    public String send(){
        mailService.sendSimpleTextMailActual("发送主题","发送内容",new String[]{"1410289853@qq.com"},new String[]{"18120691853@163.com"},null,null);
        return "1";
    }

    @ResponseBody
    @GetMapping("/user/sendMessage")
    public Result sendMessage(String email,String value){
        Result result = new Result();
        mailService.sendSimpleTextMailActual("认证结果","认证失败，"+value+"，请重新认证",new String[]{email},new String[]{"18120691853@163.com"},null,null);
        result.setCode(200);
        return result;
    }

    @ResponseBody
    @GetMapping("/user/updateUser")
    public Result updateUser(String uuid,String email){
        Result result = new Result();
        User user = new User();
        user.setUuid(uuid);
        int i = userService.updateUserAuth(user);
        if(i==1){
            result.setCode(200);
            mailService.sendSimpleTextMailActual("认证结果","认证成功",new String[]{email},new String[]{"18120691853@163.com"},null,null);
        }else{
            result.setCode(500);
        }
        return result;
    }

    @ResponseBody
    @PostMapping("/wxGetUser")
    public Result wxGetUser(@RequestBody Map<String,Object> map){
        Result result = new Result();
        String uuid = map.get("uuid").toString();
        User user = userService.findUserByUUid(uuid);
        try {
            if(user.getIsauth()==0&&user.getEmail().isEmpty()){
                result.setCode(2);
            }else if(user.getIsauth()==0&&!user.getEmail().isEmpty()){
                result.setCode(0);
            }else{
                result.setCode(user.getIsauth());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<User> userList = new ArrayList<>();
        userList.add(user);
        result.setData(userList);
        return result;
    }

    @DeleteMapping("/delUser/{uuid}")
    @ResponseBody
    public Result delTag(@PathVariable("uuid") String uuid) {
        Result result = new Result();
        String[] s = uuid.split(",");
        for (String s1 : s) {
            userService.deleteUserById(s1);
        }
        result.setCode(200);
        return result;
    }

    @GetMapping("/wxGetOpenId")
    @ResponseBody
    public Result wxGetOpenId(String code) {
        Result result = new Result();
//        System.out.println(nickname+"---"+gender+"---"+avatarUrl);
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        Map<String, String> param = new HashMap<>();
        param.put("appid", "wxd8d733d509f01a0f");
        param.put("secret", "2c114898d94cc66f43110bbfaf69c70f");
        param.put("js_code", code);
        param.put("grant_type", "authorization_code");
        String wxResult = HttpClientUtil.doGet(url, param);
        WXSession wxSession = JSON.parseObject(wxResult, WXSession.class);
        String openid = wxSession.getOpenid();
        result.setMsg(openid);
        /*User user = userService.findUserByOpenId(openid,nickname,gender,avatarUrl);
        System.out.println(openid+ UUID.randomUUID());
        if (user != null){
            result.setMsg(user.getUuid());
            result.setCode(200);
        }else{
            String uuid = userService.addUserByWX(openid,nickname,gender,avatarUrl);
            result.setMsg(uuid);
            result.setCode(200);
        }*/
        return result;
    }

/*    @GetMapping("/user/sign")
    @ResponseBody
    public Result sign(String sign,String meetingId) {
        Result result = new Result();
        List<User> userList = userService.findUserSign(sign,meetingId);
        return result;
    }*/
    @GetMapping("/user/sign1")
    @ResponseBody
    public Result sign1(Integer sign,
                              String meetingId,
                              @RequestParam int page,
                              @RequestParam int limit) {
        Result result = new Result();
        List<User> userList = userService.findUserSign(sign.toString(),meetingId);
        result.setData(userList);
        result.setCode(0);
        return result;
    }

    @GetMapping("/user/sign")
    public String sign(Integer sign,
                           String meetingId,Model model){
        model.addAttribute("sign",sign.toString());
        model.addAttribute("meetingId",meetingId);
        return "user/user/sign";
    }

    @ResponseBody
    @PostMapping("/sendCode")
    public Result sendCode(@RequestBody Map<String,Object> map){
        Result result = new Result();
        String email = map.get("email").toString();
        String code = map.get("code").toString();
        mailService.sendSimpleTextMailActual("实名认证邮箱修改","验证码为："+code,new String[]{email},new String[]{"18120691853@163.com"},null,null);
        return result;
    }
    @ResponseBody
    @PostMapping("/updateEmail")
    public Result updateEmail(@RequestBody Map<String,Object> map){
        Result result = new Result();
        String uuid = map.get("uuid").toString();
        String email = map.get("email").toString();
        userService.updateEmail(uuid,email);
        result.setCode(200);
        return result;
    }
}
